package com.gp.study.mybatis.executor;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.gp.study.mybatis.cache.CacheKey;

public class CacheExecutor implements Executor {
	
	/**
	 * 存放缓存数据
	 */
	private static final Map<Integer, Object> cache = new HashMap<>();
	
	private Executor delegate;
	
	public CacheExecutor(Executor delegate) {
		this.delegate = delegate;
	}

	@Override
	public <T> T query(String statement, Object[] parameter, Class<?> pojo)
			throws SQLException {
		CacheKey cacheKey = new CacheKey();
		cacheKey.update(statement);
		cacheKey.update(joinStr(parameter));
		Object find = cache.get(cacheKey.getCode());
		if(null!= find){
			return (T) find;
		}
		Object query = delegate.query(statement, parameter, pojo);
		cache.putIfAbsent(cacheKey.getCode(),query);
		return (T) query;
	}
	
	
	// 为了命中缓存，把Object[]转换成逗号拼接的字符串，因为对象的HashCode都不一样
    public String joinStr(Object[] objs){
        StringBuffer sb = new StringBuffer();
        if(objs !=null && objs.length>0){
            for (Object objStr : objs) {
                sb.append(objStr.toString() + ",");
            }
        }
        int len = sb.length();
        if(len >0){
            sb.deleteCharAt(len-1);
        }
        return  sb.toString();
    }

}
